package com.googlecode.flyway.core.migration.sql;

import com.googlecode.flyway.core.util.ClassPathResource;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SqlImportResolver {

    public static final SqlImportResolver NULL = new SqlImportResolver(null, null) {
        @Override
        public String resolve(String line) {
            return line;
        }
    };

    private final ClassPathResource scriptResource;
    private final String encoding;

    public SqlImportResolver(ClassPathResource scriptResource, String encoding) {
        this.scriptResource = scriptResource;
        this.encoding = encoding;
    }

    public String resolve(String line) {
        Pattern pattern = Pattern.compile("@import\\s+(.+)\\s*");
        Matcher matcher = pattern.matcher(line);
        if (matcher.find()) {
            String location = matcher.group(1);
            if (location.startsWith("/")) {
                location = location.substring(1);
            } else {
                location = scriptResource.getParentLocation() + "/" + location;
            }
            return new ClassPathResource(location).loadAsString(encoding);
        } else {
            return line;
        }
    }
}
